import {Button, Form, Row, Col, Input, Select, message} from 'antd'
import React, {useState, useEffect} from 'react'
import {history} from 'umi'
import styles from './index.less'
import Modal from '@/components/Modal'
import {getDict} from '@/service/common/dict'
import {getAllParking} from '@/service/storage/archives'
import {getFreeStoreList} from '@/service/storage/parkingLot'
import {addWarehousein} from '@/service/storage/inAtorage'
import MaterialTable from '../../components/MaterialTable'
import VehicleTable from '../../components/VehicleTable'
import {getTableList} from '@/service/purchase/plan'

const {TextArea} = Input

const add = (props: any) => {
	const {query} = props.location
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [inWarehouseType, setInWarehouseType] = useState('')
	const [form] = Form.useForm()
	const [formData, setFormData] = useState<any>({})
	const [dictData, setDictData] = useState<any>()
	const [warehouseData, setWarehouseData] = useState<any>([])
	// 选中的入库仓信息
	const [inWarehouse, setInWarehouse] = useState<any>()
	// 库位数据
	const [warehouseLocationData, setWarehouseLocationData] = useState<any>([])
	// 选中的库位信息
	const [warehouseLocation, setwarehouseLocation] = useState<any>([])
	// 选择的列表数据
	const [dataList, setDataList] = useState<any>([])
	const [btnLoading, setBtnLoading] = useState(false)
	const [procureList, setProcureList] = useState<any[]>([])
	const [valueNo, setValueNo] = useState<string>()

	// 获取采购下拉数据
	const onListFun = (value: string) => {
		getTableList({
			current: 1,
			size: 20,
			auditStatus: 1,
			planNo: value,
		}).then((res: any) => {
			if (res?.data?.records) {
				setProcureList(() => res.data.records)
			}
		})
	}
	const handleSearch = (newValue: string) => {
		if (newValue) {
			if (inWarehouseType === '1') {
				onListFun(newValue)
			} else {
				setProcureList([])
			}
		} else {
			setProcureList([])
		}
	}
	const handleChange = (newValue: string) => {
		setValueNo(newValue)
	}

	/** 获取仓库列表 */
	const getWarehouseData = () => {
		const queryData =
			query?.type === 'vehicle'
				? {
						warehouseType: '1',
				  }
				: {}
		getAllParking(queryData)
			.then((res: any) => {
				setWarehouseData(res.data)
			})
			.catch(() => {
				setWarehouseData([])
			})
	}

	useEffect(() => {
		if (inWarehouse?.id) {
			form.setFieldsValue({warehouseLocationCode: undefined})
			getFreeStoreList({parkId: inWarehouse?.id}).then((res: any) => {
				if (res?.data) {
					setWarehouseLocationData(res?.data)
				}
			})
		}
	}, [inWarehouse])

	useEffect(() => {
		getWarehouseData()
		getDict(
			{
				dictKeys: [
					'IN_WAREHOUSE_STATUS',
					'IN_WAREHOUSE_TYPE',
					'storage_large_classify',
					'storage_middle_classify',
					'Company',
				],
			},
			(res: any) => {
				if (query?.type === 'material') {
					const newData = res.IN_WAREHOUSE_TYPE.filter(
						(item: {dictValue: string}) =>
							item?.dictValue === '采购入库' ||
							item?.dictValue === '其他入库',
					)
					setDictData({...res, IN_WAREHOUSE_TYPE: newData})
				} else {
					setDictData(res)
				}
			},
		)
	}, [])
	const onSave = async () => {
		const value = await form.validateFields()
		if (value) {
			if (dataList?.length !== 0) {
				if (
					dataList.find(
						(item: {goodsQuantity: any}) =>
							!item?.goodsQuantity ||
							!Number(item?.goodsQuantity) ||
							Number(item?.goodsQuantity) >= 1000000000,
					)
				) {
					message.warning('请填写正确的入库数量')
				} else {
					setFormData({
						...value,
						inWarehouseName: inWarehouse?.warehouseName,
						warehouseLocation: warehouseLocation?.id,
						orgId: inWarehouse?.orgId,
						cityId: inWarehouse?.cityId,
						warehouseInoutGoodsList: dataList,
					})
					setIsModalOpen(true)
				}
			} else {
				const warn =
					query?.type === 'vehicle' ? '请选择车辆' : '请添加物料'
				message.warning(warn)
			}
		}
	}
	const onSubmit = () => {
		setBtnLoading(true)
		addWarehousein({...formData})
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
				setBtnLoading(false)
			})
			.catch((err: any) => {
				message.error(err)
				setBtnLoading(false)
			})
	}

	return (
		<div className={styles.add}>
			<div className={styles.title}>基础信息</div>
			<Form
				form={form}
				name="basic"
				layout="horizontal"
				labelCol={{flex: '120px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off">
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="状态"
							name="inWarehouseStatus"
							rules={[{required: true}]}>
							<Select
								placeholder="请选择"
								allowClear
								fieldNames={{
									value: 'dictKey',
									label: 'dictValue',
								}}
								options={dictData?.IN_WAREHOUSE_STATUS}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="入库类型"
							name="inWarehouseType"
							rules={[{required: true}]}>
							<Select
								placeholder="请选择"
								allowClear
								fieldNames={{
									value: 'dictKey',
									label: 'dictValue',
								}}
								onChange={(value) => {
									setInWarehouseType(value)
									form.setFieldsValue({
										sourceDocNo: undefined,
									})
									setProcureList([])
								}}
								options={dictData?.IN_WAREHOUSE_TYPE}
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item label="来源单号" name="sourceDocNo">
							{inWarehouseType === '1' ? (
								<Select
									showSearch
									value={valueNo}
									placeholder={props.placeholder}
									style={props.style}
									defaultActiveFirstOption={false}
									showArrow={false}
									filterOption={false}
									onSearch={handleSearch}
									onChange={handleChange}
									notFoundContent={null}
									options={(procureList || []).map((d) => ({
										value: d.planNo,
										label: d.planNo,
									}))}
								/>
							) : (
								<Input placeholder="请输入" />
							)}
						</Form.Item>
					</Col>
					{query?.type === 'vehicle' && inWarehouseType === '2' ? (
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="出库仓"
								name="outWarehouse"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									allowClear
									options={[]}
								/>
							</Form.Item>
						</Col>
					) : (
						''
					)}
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="入库仓"
							name="inWarehouse"
							rules={[{required: true}]}>
							{query?.type === 'vehicle' &&
							inWarehouseType === '2' ? (
								<Input
									placeholder="根据选择车辆的入库仓回填"
									disabled
								/>
							) : (
								<Select
									placeholder="请选择"
									allowClear
									showSearch
									optionFilterProp="warehouseName"
									fieldNames={{
										value: 'id',
										label: 'warehouseName',
									}}
									onSelect={(value: any, key: any) => {
										setInWarehouse(key)
									}}
									options={warehouseData}
								/>
							)}
						</Form.Item>
					</Col>
					{query?.type === 'vehicle' ? (
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
							<Form.Item
								label="库位"
								name="warehouseLocationCode"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									allowClear
									fieldNames={{
										value: 'storageCode',
										label: 'storageCode',
									}}
									onSelect={(value: any, key: any) => {
										setwarehouseLocation(key)
									}}
									options={warehouseLocationData}
								/>
							</Form.Item>
						</Col>
					) : (
						''
					)}
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item label="送货人" name="deliveryMan">
							<Input placeholder="请输入" />
						</Form.Item>
					</Col>
					<Col span={16} style={{marginRight: '20px'}}>
						<Form.Item label="验收结果说明" name="remark">
							<TextArea
								maxLength={200}
								placeholder="请输入（最多200个字）"
								autoSize={{minRows: 3, maxRows: 6}}
							/>
						</Form.Item>
					</Col>
				</Row>
			</Form>
			{query?.type === 'vehicle' ? (
				<VehicleTable
					data={dataList}
					setDataList={setDataList}
					edit
					inWarehouse={inWarehouse}
					inWarehouseType={inWarehouseType}
				/>
			) : (
				<MaterialTable
					data={dataList}
					edit
					dictData={dictData}
					setDataList={setDataList}
				/>
			)}
			<div className={styles.wrap}>
				<Button
					type="primary"
					htmlType="submit"
					onClick={() => {
						onSave()
					}}>
					保存
				</Button>
				<Button
					onClick={() => {
						history.go(-1)
					}}>
					取消
				</Button>
			</div>
			<Modal
				text="确定要保存吗？请仔细核对所填信息"
				onSubmit={onSubmit}
				loading={btnLoading}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
		</div>
	)
}

export default add
